import { RouteRecordRaw } from 'vue-router'
import { fetchRoutes, fetchUserPermissions } from '@/api/route'
import router from '@/router'

// 定义状态类型
interface RouteState {
  routes: RouteRecordRaw[];
  permissions: string[];
  isRoutesLoaded: boolean;
  isLoadingRoutes: boolean;
  loadError: string | null;
}

// 初始状态
const state: RouteState = {
  routes: [],
  permissions: [],
  isRoutesLoaded: false,
  isLoadingRoutes: false,
  loadError: null
}

// Mutations：修改状态
const mutations = {
  SET_ROUTES(state: RouteState, routes: RouteRecordRaw[]) {
    state.routes = routes
  },
  SET_PERMISSIONS(state: RouteState, permissions: string[]) {
    state.permissions = permissions
  },
  SET_ROUTES_LOADED(state: RouteState, loaded: boolean) {
    state.isRoutesLoaded = loaded
  },
  SET_LOADING_ROUTES(state: RouteState, loading: boolean) {
    state.isLoadingRoutes = loading
  },
  SET_LOAD_ERROR(state: RouteState, error: string | null) {
    state.loadError = error
  },
  RESET_ROUTES(state: RouteState) {
    state.routes = []
    state.permissions = []
    state.isRoutesLoaded = false
    state.loadError = null
  }
}

// Actions：异步操作
const actions = {
  // 加载动态路由
  async loadDynamicRoutes({ state, commit }: any): Promise<boolean> {
    if (state.isRoutesLoaded) {
      return true // 如果已经加载过，直接返回成功
    }

    commit('SET_LOADING_ROUTES', true)
    commit('SET_LOAD_ERROR', null)

    try {
      // 加载用户权限
      const userPermissions = await fetchUserPermissions()
      commit('SET_PERMISSIONS', userPermissions)

      // 加载路由配置
      const asyncRoutes = await fetchRoutes()
      // commit('SET_ROUTES', asyncRoutes)

      // 创建一个主布局路由，将所有动态路由作为其子路由
      const mainLayoutRoute: RouteRecordRaw = {
        path: '/',
        name: 'MainLayout',
        component: () => import('@/layouts/MainLayout.vue'), // 需要创建这个布局组件
        children: asyncRoutes,
        redirect: asyncRoutes.length > 0 ? asyncRoutes[0].path : '/dashboard'
      }

      // 移除现有的根路由重定向
      if (router.hasRoute('MainLayout')) {
        router.removeRoute('MainLayout')
      }
      
      // 添加主布局路由
      console.log('mainLayoutRoute',mainLayoutRoute)
      router.addRoute(mainLayoutRoute)

      console.log('routes',router.getRoutes())

      commit('SET_ROUTES_LOADED', true)
      return true
    } catch (error) {
      console.error('加载动态路由失败:', error)
      commit('SET_LOAD_ERROR', error instanceof Error ? error.message : '未知错误')
      return false
    } finally {
      commit('SET_LOADING_ROUTES', false)
    }
  },

  // 重置路由状态
  resetRoutes({ state, commit }: any) {
    // 移除主布局路由（这将同时移除所有子路由）
    if (router.hasRoute('MainLayout')) {
      router.removeRoute('MainLayout')
    }

    // 以防万一，也移除所有单独的动态路由
    state.routes.forEach((route: RouteRecordRaw) => {
      if (router.hasRoute(route.name as string)) {
        router.removeRoute(route.name as string)
      }
    })

    commit('RESET_ROUTES')
  }
}

// Getters：计算属性
const getters = {
  getRoutes: (state: RouteState) => state.routes,
  getPermissions: (state: RouteState) => state.permissions,
  isRoutesLoaded: (state: RouteState) => state.isRoutesLoaded,
  isLoadingRoutes: (state: RouteState) => state.isLoadingRoutes,
  getLoadError: (state: RouteState) => state.loadError
}

// 导出路由模块
export const routeModule = {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
} 